package com.atguigu.gulimall.ssoclient.controller;

import com.atguigu.common.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @version 1.0
 * @Author yanjingren
 * @Date 2021/6/16
 * @Description com.atguigu.gulimall.ssoclient.controller
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 无需登录就可访问
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     * 需要验证的连接
     * 感知ssoserver登录成功跳回来的，而不是直接访问的
     * @param model
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(name = "token", required = false, defaultValue = "") String token) throws Exception {
        if (!StringUtils.isEmpty(token)) {
            HttpResponse response = HttpUtils.doGet("http://ssoserver.com:8080", "/userInfo", "get", new HashMap<String, String>(), null);
            session.setAttribute("loginUser", response.getEntity());
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 没登录，跳转到登录服务器进行登录
            // 跳转过去之后，使用url上的查询参数，表示自己是哪个页面
//            String username = stringRedisTemplate.opsForValue().get(token);
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
//            model.addAttribute("username", username);
            return "list";
        }
    }
}
